package com.meixiang.adapter.personalCenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.myAppointment.AppointmentDetailActivity;
import com.meixiang.activity.account.myAppointment.AppointmentEvaluationActivity;
import com.meixiang.activity.account.myAppointment.MyAllAppointmentActivity;
import com.meixiang.activity.account.myShopper.OrderRefundActivity;
import com.meixiang.activity.homes.shopping.CashierDeskActivity;
import com.meixiang.dialog.CustomPopup;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.myOrder.OrderUtils;
import com.meixiang.entity.servicOrder.AllServiceOrderResult;
import com.meixiang.entity.servicOrder.ServiceRefundResult;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.recyclerview.RecyclerAdapter;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.DensityUtil;
import com.meixiang.util.GlideHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author xyj
 */
public class AllAppointmentAdapter extends RecyclerAdapter<AllAppointmentAdapter.ViewHolder> {
    private Context context;
    private String status;
    private View view;
    private CustomPopup pop;
    private Activity mActivity;
    private List<AllServiceOrderResult.ServiceOrderGoodsList> serviceOrders;
    private List<ServiceRefundResult.RefundList> refundLists;

    public AllAppointmentAdapter(Context context, String status, Activity mActivity) {
        this.context = context;
        this.status = status;
        this.mActivity = mActivity;
    }

    public void refreshData(List<AllServiceOrderResult.ServiceOrderGoodsList> serviceOrders) {
        this.serviceOrders = serviceOrders;
        notifyDataSetChanged();
    }

    public void refreshRefundData(List<ServiceRefundResult.RefundList> refundLists) {
        if (refundLists != null && refundLists.size() != 0) {
            this.refundLists = refundLists;
            notifyDataSetChanged();
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.activity_my_all_appointment_list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public long getItemId(int position) {
        setHasStableIds(false);
        return position;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final String orderStatus;
        /*if (!AbStrUtil.isEmpty(status)) {
            orderStatus = status;
        } else {*/

            //订单状态：0:已取消;10:待付款;30:待使用;40:交易完成(已使用);
        //}
        if ("退款/售后".equals(status)) {
            if ("0".equals(refundLists.get(position).getIsMainStore())) { //加盟店
                holder.tvName.setText("加盟店");
            } else {
                holder.tvName.setText("总店商品");
            }
            holder.tv_check_logistics.setVisibility(View.GONE);
            holder.tv_check_receipt.setText("退款详情");
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_status_color));
            holder.tvStatus.setText(OrderUtils.getServiceRefund(refundLists.get(position).getRefundState()));
            holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
            holder.all_appointment_item_tv_detail.setText(refundLists.get(position).getGoodsName());
            holder.tvMoney.setText("￥" + refundLists.get(position).getRefundAmount());
            if (!AbStrUtil.isEmpty(refundLists.get(position).getGoodsImage())) {
                GlideHelper.showImage(context, refundLists.get(position).getGoodsImage(), R.drawable.image_default_white_bg, holder.all_appointment_item_iv);
            }
            holder.rl_goods_info_layout.setOnClickListener(new View.OnClickListener() { //预约详情
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(context, AppointmentDetailActivity.class);
                    intent.putExtra("status", status);
                    intent.putExtra("order_state",OrderUtils.getServiceRefund(refundLists.get(position).getRefundState()));
                    intent.putExtra("refundId", refundLists.get(position).getRefundId());
                    intent.putExtra("typeId", refundLists.get(position).getTypeId());
                    intent.putExtra("gcId", refundLists.get(position).getGcId());
                    context.startActivity(intent);
                }
            });
            holder.tv_check_receipt.setOnClickListener(new View.OnClickListener() { //查看退款详情页
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, OrderRefundActivity.class);
                    intent.putExtra("refundId", refundLists.get(position).getRefundId()); //订单商品Id
//                    intent.putExtra("goodsId", refundLists.get(position).getGoodsId()); //商品Id
//                    intent.putExtra("specId", refundLists.get(position).getSpecId()); //规格Id
//                    intent.putExtra("storeId", refundLists.get(position).getStoreId()); //店铺id
//                    intent.putExtra("orderId", refundLists.get(position).getOrderId()); //订单id
                    context.startActivity(intent);
                }
            });

        } else {
            orderStatus = OrderUtils.getServiceOrderStatus(serviceOrders.get(position).getOrderState(),serviceOrders.get(position).getEvaluationStatus(),"");
            if ("0".equals(serviceOrders.get(position).getIsMainStore())) { //加盟店
                holder.tvName.setText("加盟店");
            } else {
                holder.tvName.setText("总店商品");
            }
            if (orderStatus.equals("待使用")) {
                holder.tv_check_logistics.setVisibility(View.GONE);
                holder.tvStatus.setText("待使用");
                holder.tv_check_receipt.setText("查看券码");
                holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_status_color));
            } else if (orderStatus.equals("待评价")) {
                holder.tv_check_logistics.setVisibility(View.VISIBLE);
                holder.tv_check_logistics.setText("评价服务");
                holder.tvStatus.setText("待评价");
                holder.tv_check_receipt.setText("删除订单");
                holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_green_color));
            } else if (orderStatus.equals("待付款")) {
                holder.tv_check_logistics.setVisibility(View.VISIBLE);
                holder.tv_check_logistics.setText("取消订单");
                holder.tv_check_receipt.setText("去支付");
                holder.tvStatus.setText("待支付");
                holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
            } else if (orderStatus.equals("交易完成")) {
                holder.tv_check_logistics.setVisibility(View.GONE);
                holder.tvStatus.setText("交易完成");
                holder.tv_check_receipt.setText("删除订单");
                holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
            } else if (orderStatus.equals("已取消")) {
                holder.tv_check_logistics.setVisibility(View.GONE);
                holder.tvStatus.setText("已取消");
                holder.tv_check_receipt.setVisibility(View.GONE);
                holder.tvStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
            }

            if("0".equals(serviceOrders.get(position).getPaymentState())){
                holder.appointment_item_tv_disbursements.setText("待付款:");
            }else if("1".equals(serviceOrders.get(position).getPaymentState())){
                holder.appointment_item_tv_disbursements.setText("已付款:");
            }
            holder.tvStatus.setText(orderStatus);
            holder.all_appointment_item_tv_detail.setText(serviceOrders.get(position).getGoodsName());
            holder.tvMoney.setText("￥" + serviceOrders.get(position).getOrderAmount());
            if (!AbStrUtil.isEmpty(serviceOrders.get(position).getGoodsImage())) {
                GlideHelper.showImage(context, serviceOrders.get(position).getGoodsImage(), R.drawable.image_default_white_bg, holder.all_appointment_item_iv);
            }

            holder.rl_goods_info_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, AppointmentDetailActivity.class);
                    intent.putExtra("status", orderStatus);
                    intent.putExtra("orderId", serviceOrders.get(position).getOrderId());
                    intent.putExtra("typeId", serviceOrders.get(position).getTypeId());
                    intent.putExtra("gcId", serviceOrders.get(position).getGcId());
                    context.startActivity(intent);
                }
            });
            holder.tv_check_logistics.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickTvCheckLogistics(holder, position);
                }
            });
            holder.tv_check_receipt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickTvCheckReceipt(holder, position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        if ("退款/售后".equals(status)) {
            return refundLists == null ? 0 : refundLists.size();
        } else {
            return serviceOrders == null ? 0 : serviceOrders.size();
        }
    }

    /**
     * 初始化一个弹出的窗体
     */
    private void initPopupWindow(String servicePwd) {
        view = LayoutInflater.from(context).inflate(R.layout.dialog_show_ticket_number, null);
        pop = new CustomPopup(context, mActivity, view, DensityUtil.dip2px(context, 40), R.mipmap.passwordbg);
        TextView text_pass = (TextView) view.findViewById(R.id.tv_service_pass);
        if (!TextUtils.isEmpty(servicePwd)) {
            text_pass.setText(servicePwd);
        }
    }

    /**
     * 点击左边按钮
     *
     * @param holder
     */
    private void clickTvCheckLogistics(ViewHolder holder, final int position) {
        if (holder.tv_check_logistics.getText().toString().equals("取消订单")) {
            //取消订单
            cancelOrder(position);
            return;
        } else if (holder.tv_check_logistics.getText().toString().equals("评价服务")) {
            //评价服务
            Intent intent = new Intent(context, AppointmentEvaluationActivity.class);
            intent.putExtra("o2oService.o2oServiceOrderId", serviceOrders.get(position).getOrderId());
            intent.putExtra("typeId", serviceOrders.get(position).getTypeId());
            intent.putExtra("gcId", serviceOrders.get(position).getGcId());
            intent.putExtra("orderName", serviceOrders.get(position).getGoodsName());
            intent.putExtra("goodimage", serviceOrders.get(position).getGoodsImage());
            intent.putExtra("beautician.o2oServiceOrderId", serviceOrders.get(position).getGoodsId());
            context.startActivity(intent);
        } else {
            return;
        }
    }


    /**
     * 取消预约订单
     */
    private void cancelOrder(final int position) {
        HttpParams params = new HttpParams();
        params.put("orderId", serviceOrders.get(position).getOrderId());
        HttpUtils.post(Config.SERVICE_ORDER_CANCEL, params, new HttpCallBack(mActivity, "数据请求中") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context, message);
                serviceOrders.remove(position);
                notifyDataSetChanged();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }

    /**
     * 删除预约订单
     *
     * @param position
     */
    private void deleteOrder(final int position) {
        HttpParams params = new HttpParams();
        params.put("orderId", serviceOrders.get(position).getOrderId());
        HttpUtils.post(Config.SERVICE_ORDER_DELETE, params, new HttpCallBack(mActivity, "数据请求中") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context, message);
                serviceOrders.remove(position);
                notifyDataSetChanged();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }

    /**
     * 点击右边按钮
     *
     * @param holder
     */
    private void clickTvCheckReceipt(ViewHolder holder, final int position) {

        if (holder.tv_check_receipt.getText().toString().equals("查看券码")) {
            if (serviceOrders.get(position).getServicePwd() != null && serviceOrders.get(position).getServicePwd().size() != 0) {
                initPopupWindow(serviceOrders.get(position).getServicePwd().get(0));
            } else {
                Tool.showTextToast(context, "暂无服务密码");
                return;
            }
            // 计算x轴方向的偏移量，使得PopupWindow在Title的正下方显示，此处的单位是pixels
            int xoffInPixels = Tool.getWindowWith(context) / 2 - (holder.tv_check_receipt.getLayoutParams().width);
            // 将pixels转为dip
            int xoffInDip = DensityUtil.px2dip(context, xoffInPixels);
            if (pop.isShowing()) {
                pop.dismiss();
            } else {
                int popupHeight = pop.getHeight();
                int[] location = new int[2];
                holder.tv_check_receipt.getLocationOnScreen(location); //获得在屏幕上的位置
                if (Tool.getWindowHeight(context) - location[1] < 100) { // 区分显示在按钮上方还是下方
                    pop.setBackgroundDrawable(ContextCompat.getDrawable(context, R.mipmap.passwordbg2));
                    pop.showAtLocation(holder.tv_check_receipt, Gravity.NO_GRAVITY, xoffInDip + (holder.tv_check_receipt.getMeasuredWidth() / 2), location[1] - popupHeight + holder.tv_check_receipt.getLayoutParams().height);
                } else {
                    pop.setBackgroundDrawable(ContextCompat.getDrawable(context, R.mipmap.passwordbg));
                    pop.showAsDropDown(holder.tv_check_receipt, -xoffInDip, 0);
                }
                pop.update();
            }
        } else if (holder.tv_check_receipt.getText().toString().equals("去支付")) {
            Intent intents = new Intent(context, CashierDeskActivity.class);
            String type = "";
            if ("1".equals(serviceOrders.get(position).getTypeId())) {
                //美服务
                type = GlobalType.SERVICE_TYPE;
                intents.putExtra(CashierDeskActivity.ORDER_TYPE,"FW");
            } else if ("2".equals(serviceOrders.get(position).getTypeId())) {
                //2美容培训
                type = GlobalType.TRAIN_TYPE;
                intents.putExtra(CashierDeskActivity.ORDER_TYPE,"PX");
            }

            OrderResult mOrderResult = new OrderResult(serviceOrders.get(position).getOrderAmount(), serviceOrders.get(position).getOrderId(), type);

            intents.putExtra(CashierDeskActivity.ORDER_RESULT, mOrderResult);

            intents.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY);
            HashMap<String, Class> map = new HashMap<>();
            map.put(CashierDeskActivity.GOTO_ACTIVITY, MyAllAppointmentActivity.class);
            intents.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
            context.startActivity(intents);

        } else if (holder.tv_check_receipt.getText().toString().equals("删除订单")) { //删除订单
            deleteOrder(position);
        } else {
            Tool.showTextToast(context, holder.tv_check_receipt.getText().toString());
        }


    }

    class ViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.appointment_item_tv_name)
        TextView tvName;
        @Bind(R.id.appointment_item_tv_status)
        TextView tvStatus;
        @Bind(R.id.appointment_item_tv_money)
        TextView tvMoney;
        @Bind(R.id.appointment_item_tv_check_logistics)
        TextView tv_check_logistics;
        @Bind(R.id.appointment_item_tv_check_receipt)
        TextView tv_check_receipt;
        @Bind(R.id.rl_goods_info_layout)
        RelativeLayout rl_goods_info_layout; //商品信息
        @Bind(R.id.all_appointment_item_iv)
        ImageView all_appointment_item_iv; //服务图片
        @Bind(R.id.all_appointment_item_tv_detail)
        TextView all_appointment_item_tv_detail;
        @Bind(R.id.appointment_item_tv_disbursements)
        TextView appointment_item_tv_disbursements;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
